In this tutorial, we will learn how to print a page or a specific div in Vue 3 (Composition API). We will use the window.print()
method to print the page. Whether you’re looking to create printable reports, invoices, or any other document.
Example 1 : Use Vue 3 to Print Current Page
In the example below, we provide code to print the entire page using Vue 3. We utilize the print.window
method to achieve this.
Vue 3 Print Page (Composition Api)
<script type="module">
const {createApp} = Vue;
createApp({
setup() {
const printPage = () => {
window.print();
};
return {
printPage
};
}
}).mount("#app");
</script>
Example 2: How to Print Specfic Div in Vue 3?
In this second example of this tutorial, we will learn how to print a specific div of the page, use “try it,” customize the code, and apply it to your project.
Print Div in Vue 3
<script type="module">
const {createApp,ref} = Vue;
createApp({
setup() {
const contentToPrint = ref(null);
const printContent = () => {
let newWin = window.open('', '_blank');
newWin.document.write(contentToPrint.value.innerHTML);
newWin.document.close();
newWin.print();
};
return {
contentToPrint,
printContent
};
}
}).mount("#app");
</script>